# coding:utf-8

from . import api
from launch.utils.commons import login_required
from flask import g, request, current_app, jsonify, session
from launch.utils.response_code import RET
from launch.utils.image_storage import storage
from launch.models import User
from launch import db, constants
import re


@api.route("/users/avatar", methods=['post'])
@login_required
def set_user_avatar():
    """
    设置用户的头像
    @:param 图片(多媒体表单格式)  用户id(g.user_id)
    :return:
    """
    # 装饰器的代码中已经将user_id保存到g对象中，所以视图中可以直接读取
    user_id = g.user_id
    # 获取图片
    image_file = request.files.get("avatar")
    if image_file is None:
        return jsonify(errno=RET.PARAMERR, errmsg="未上传图片")

    image_data = image_file.read()

    # 调用七牛上传图片
    try:
        file_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(3)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

    # 保存文件名到数据库中
    try:
        User.query.filter_by(id=user_id).update({"avatar_url": file_name})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存图片信息失败")

    avatar_url = constants.QINIU_URL_DOMAIN + file_name
    # 保存成功返回
    return jsonify(errno=RET.OK, errmsg="保存成功", data={"avatar_url": avatar_url})


@api.route("/users/name", methods=['put'])
@login_required
def change_user_name():
    """
    修改用户名
    :return:
    """
    user_id = g.user_id
    req_dict = request.get_json()
    if not req_dict:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    name = req_dict.get("name")
    if not all([name]):
        return jsonify(errno=RET.PARAMERR, errmsg="名字不能为空")

    try:
        User.query.filter_by(id=user_id).update({"name": name})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="设置用户名错误")

    # 修改session数据中的name字段
    session["name"] = name
    return jsonify(errno=RET.OK, errmsg="修改用户名成功")


@api.route("/user", methods=['get'])
@login_required
def get_user_profile():
    """
    获取用户信息
    :return:
    """
    user_id = g.user_id

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户信息失败")

    if user is None:
        return jsonify(errno=RET.NODATA, errmsg="无效操作'")

    # avatar_url = constants.QINIU_URL_DOMAIN + user.avatar_url
    # return jsonify(errno=RET.OK, errmsg="true",
    #                data={"name": user.name, "mobile": user.mobile, "avatar_url": avatar_url})
    return jsonify(errno=RET.OK, errmsg='OK', data=user.to_dict())


@api.route("/user/auth", methods=['get', 'post'])
@login_required
def get_user_auth():
    """
    获取用户实名认证信息
    可拆分成get,post请求,拆分成两个函数
    :return:
    """
    user_id = g.user_id

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户实名信息失败")

    if user is None:
        return jsonify(errno=RET.NODATA, errmsg="无效操作")

    if request.method == "GET":
        return jsonify(errno=RET.OK, errmsg="OK", data=user.auth_to_dict())
    elif request.method == "POST":
        req_dict = request.get_json()
        if not req_dict:
            return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

        id_card = req_dict.get("id_card")
        real_name = req_dict.get("real_name")

        if not all([id_card, real_name]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

        if not re.match(constants.ID_CARD_REGEX, id_card):
            return jsonify(errno=RET.PARAMERR, errmsg="身份证输入错误")

        # user.id_card = id_card
        # user.real_name = real_name
        try:
            User.query.filter_by(id=user_id, real_name=None, id_card=None).update(
                {"real_name": real_name, "id_card": id_card})
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="保存用户实名信息失败")
        return jsonify(errno=RET.OK, errmsg="OK")
